/**
 * loading no 表示不需要加载提示
 * Created by yangyang on 2017/2/17.
 */

//self.ifSub 默认加载

const instance = function ($this, subConfig, Vue) {
  const self = $this;
  //只有formName存在时进入表单验证，否则直接发起请求
  if (!subConfig.formName) {
    sub_($this, subConfig, Vue);
  } else {
    $this.$refs[subConfig.formName].validate(function (valid) {
      if (valid) {
        sub_($this, subConfig, Vue);
      } else {
        self.$message.error({
          showClose: true,
          message: "内容填写不正确，请重试！"
        });
      }
    });
  }
};

function sub_(self, subConfig, Vue) {
  if (subConfig.loading) {
    if (subConfig.loading != "no")
      self[subConfig.loading] = true
  } else {
    self.ifSub = true;
  }
  self.$store.commit('cacheDataUpdate', {
    name: 'loadingBarActive',
    value: true
  });
  let url = subConfig.url.path;
  //设置地址参数 /{id}
  if (subConfig.params) {
    for (let key in subConfig.params) {
      url = url.replace('{' + key + '}', encodeURIComponent(subConfig.params[key]))
    }
  }
  let config = {
    url: url,
    method: subConfig.url.method,
  };
  if (subConfig.url.method === 'GET') {
    config['params'] = subConfig.data
  } else {
    config['data'] = subConfig.data
  }
  Vue.http.request(config).then(data => {
    if (data.code == 0) {
      if (subConfig.callback != undefined) {
        subConfig.callback(data);
      }
      if (!subConfig.noTips) {
        self.$message.success({
          showClose: true,
          message: data.message
        });
      }
    } else {
      let message = data.message;
      if (data.response) {
        if (data.response.status === 401) {
          message = "登陆已经过期，请重新登录！"
        }
      }
      self.$message.error({
        showClose: true,
        message: message
      });
    }
    if (subConfig.loading) {
      if (subConfig.loading != "no")
        self[subConfig.loading] = false
    } else {
      self.ifSub = false;
    }
    self.$store.commit('cacheDataUpdate', {
      name: 'loadingBarActive',
      value: false
    });
  }).catch(err => {
    if (subConfig.loading) {
      if (subConfig.loading != "no")
        self[subConfig.loading] = false
    } else {
      self.ifSub = false;
    }
    self.$store.commit('cacheDataUpdate', {
      name: 'loadingBarActive',
      value: false
    });
    console.log(err);
    self.$message.error({
      showClose: true,
      message: err.message
    });
  });
}

function plugin(Vue) {
  if (plugin.installed) {
    return;
  }
  Vue.submit = instance;
}

if (typeof  window !== "undefined" && window.Vue) {
  window.Vue.use(plugin);
}

export default plugin;
